using System.IO;
using System.Net;
using Newtonsoft.Json;

namespace EasyUtils.Http
{
    public class SimpleHttpHelper : ISimpleHttpHelper
    {
        public T GetJsonData<T>(string uri)
        {
            string value = GetContent(uri);
            if (string.IsNullOrEmpty(value))
            {
                return default(T);
            }

            var result = JsonConvert.DeserializeObject<T>(value);
            return result;
        }

        public string GetContent(string uri)
        {
            WebRequest request = WebRequest.Create(uri);
            WebResponse webResponse = request.GetResponse();

            using (var responseStream = webResponse.GetResponseStream())
            {
                if (responseStream != null)
                {
                    var streamReader = new StreamReader(responseStream);
                    string readToEnd = streamReader.ReadToEnd();
                    responseStream.Close();
                    return readToEnd;
                }
            }

            return null;
        }
    }
}